import { _decorator, Animation, AnimationClip, AnimationState } from "cc";
import State from "../Base/State";
import StateMachine, { getInitParamsTrigger } from "../Base/StateMachine";

import { EAnimationPlayMode, EState, EntityType, EParamsName } from "../Config/Enum";
const { ccclass } = _decorator;

@ccclass("SkillStateMachine")
export class SkillStateMachine extends StateMachine {
  speed: any;
  animationPlayMode: EAnimationPlayMode
  wrapMode

  
  init(type: EntityType, speed:number, animationPlayMode:EAnimationPlayMode) {

    
    this.type = type;
    
    this.animationComponent = this.node.getComponent(Animation) || this.node.addComponent(Animation);

    this.speed = speed
    this.animationPlayMode = this.wrapMode = animationPlayMode;
   
    this.initParams();
    this.initStateMachines();
    this.initAnimationEvent();

  }

  initParams() {
    this.params.set(EParamsName.Idle, getInitParamsTrigger());

  }

  initStateMachines() {
    this.stateMachines.set(EParamsName.Idle, new State(this, `${this.type}${EState.Idle}`, this.wrapMode, false, this.speed));
  }

  // initAnimationEvent() {}
  initAnimationEvent() {
    this.animationComponent.on(Animation.EventType.FINISHED, (type, state) => {
        // 确保只有 Normal 模式触发结束事件 播放一次就回收
        if (this.animationPlayMode === EAnimationPlayMode.Normal ) {
            this.node.emit("SkillAnimationFinished");
        }

    }, this);
}

//|| this.animationPlayMode === EAnimationPlayMode.LoopToEnd
  onAnimationFinished(type: Animation.EventType, state: AnimationState) {
    // 只有单次播放模式才触发结束事件
    if (this.animationPlayMode === EAnimationPlayMode.Normal) {
      //if (state.name.includes(EState.Idle)) {
        this.node.emit("SkillAnimationFinished");
      //}
    }
  }
  

  run() {
    // console.log("this.currentState", this.currentState);
    switch (this.currentState) {

      case this.stateMachines.get(EParamsName.Idle):
        break;
      default:
        this.currentState = this.stateMachines.get(EParamsName.Idle);
        break;
    }
  }
}
